package com.useeinfo.oa.open.admin.inspection;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.sugar.data.QueryParam;
import com.useeinfo.framework.sugar.func.file.FileUtils;
import com.useeinfo.framework.sugar.func.lang.StringUtils;
import com.useeinfo.framework.sugar.tools.Configuration;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.config.ConstantKeyFilePath;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.DictInfoBiz;
import com.useeinfo.oa.modules.base.biz.ResourceBiz;
import com.useeinfo.oa.modules.base.entity.Enterprise;
import com.useeinfo.oa.modules.base.entity.Resource;
import com.useeinfo.oa.modules.base.enums.ResourceTypeEnum;
import com.useeinfo.oa.modules.inspection.biz.InspectionDataBiz;
import com.useeinfo.oa.modules.inspection.biz.InspectionTechnologyBiz;
import com.useeinfo.oa.modules.inspection.entity.InspectionData;
import com.useeinfo.oa.modules.inspection.entity.InspectionTechnology;
import com.useeinfo.oa.modules.inspection.enums.InputTypeEnum;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/web/admin/inspectionData")
public class InspectionDataAction {
    @Autowired
    private InspectionDataBiz inspectionDataBiz;
    @Autowired
    private InspectionTechnologyBiz inspectionTechnologyBiz;
    @Autowired
    private ResourceBiz resourceBiz;
    @Autowired
    private DictInfoBiz dictInfoBiz;

    /**
     * 跳转到添加维保内容页面
     * @return
     */
    @RequestMapping("/inspectionDataEdit")
    public ModelAndView inspectionDataEdit(@RequestParam(value = "id", required = false) String id,
                                           @RequestParam(value = "timeStamp", required = false) String timeStamp,
                                           HttpServletRequest request) {

        ModelAndView modelAndView = new ModelAndView();
        InspectionData inspectionData = inspectionDataBiz.findModel(StringConverters.ToLong(id));
        modelAndView.addObject("inspectionData",inspectionData);
        modelAndView.addObject("timeStamp",timeStamp);
        String fileName = "";
        JSONArray contentArray = new JSONArray();
        if (inspectionData != null) {
            if (inspectionData.getEnclosure() != null && inspectionData.getEnclosure().size() != 0) {
                List<Resource> resourceList = new ArrayList<>(inspectionData.getEnclosure());
                fileName = resourceList.get(0).getResourceName();
            }
            if(inspectionData.getContent()!=null){
                contentArray = JSONArray.parseArray(inspectionData.getContent());
            }
        }
        modelAndView.addObject("fileName",fileName);
        modelAndView.addObject("contentArray",contentArray);
        modelAndView.setViewName("pages/admin/inspection/inspectionData/edit");

        return modelAndView;
    }

    @RequestMapping("/listJson")
    @ResponseBody
    public JSONObject listJson(HttpServletRequest request,
                               @RequestParam(value = "id", required = false) String id,
                               @RequestParam(value = "timeStamp", required = false) String timeStamp) {
        QueryParam queryParam = new QueryParam(-1, -1);
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise!=null){
            queryParam.getSqlMap().put("enterpriseId", enterprise.getId()+"");
        }
        if(StringUtils.isNotBlank(timeStamp)){
            queryParam.getSqlMap().put("timeStamp2", timeStamp);
        }
        if(StringUtils.isNotBlank(id)){
            queryParam.getSqlMap().put("inspectionTechnologyId2", id);
        }
        return inspectionDataBiz.findJQJSONList(queryParam);
    }

    /**
     * 执行提交的新增或修改请求
     */
    @RequestMapping("/executeEdit")
    @ResponseBody
    public ResultDto executeEdit(InspectionData inspectionData, HttpServletRequest request,
                                 @RequestParam(value = "selectDictInfoId[]", required = false) List<String> selectDictInfoIds,
                                 @RequestParam(value = "array[]", required = false) List<String> contentList,
                                 @RequestParam(value = "inspectionTechnologyId", required = false) String inspectionTechnologyId,
                                 @RequestParam(value = "sImg1", required = false) String sImg1,
                                 @RequestParam(value = "pic1", required = false) MultipartFile pic1) {
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        if(enterprise==null){
            return ResultUtil.error("获取企业失败，请更新页面重试");
        }
        //应用场景不得为空
        if (CollectionUtils.isNotEmpty(selectDictInfoIds)) {
            inspectionData.setDictInfo(dictInfoBiz.findModel(StringConverters.ToLong(selectDictInfoIds.get(0))));
        }else{
            return ResultUtil.error("请选择应用场景");
        }
        //如果为输入类型为数值，则最大值最小值必填
        if(inspectionData.getInputTypeEnum()!=null&& InputTypeEnum.NUMBER.getCode().equals(inspectionData.getInputTypeEnum().getCode())){
            if(inspectionData.getMaxNumber()==null||inspectionData.getMinNumber()==null||StringUtils.isBlank(inspectionData.getUnit())){
                return ResultUtil.error("请输入最大最小值及单位");
            }
        }
        //将维保内容转成jsonArray格式字符串储存
        if(CollectionUtils.isNotEmpty(contentList)){
            JSONArray jsonArray = new JSONArray();
            for (int i = 0; i < contentList.size(); i++) {
                if(StringUtils.isNotBlank(contentList.get(i))){
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("name","巡检内容");
                    jsonObject.put("text",contentList.get(i));
                    jsonArray.add(jsonObject);
                }
            }
            inspectionData.setContent(jsonArray.toString());
        }
        if(StringUtils.isNotBlank(inspectionTechnologyId)){
            inspectionData.setInspectionTechnology(inspectionTechnologyBiz.findModel(StringConverters.ToLong(inspectionTechnologyId)));
        }
        //上传资料操作
        if ("1".equals(sImg1)) {
            //首先删除之前的关联资料文件
            inspectionData.setEnclosure(null);
            //如果有新资料文件 再存新资料文件
            String savePath1 = FileUtils.fileUpload(pic1, ConstantKeyFilePath.INSPECTION_DATA_PDF_DIR, ConstantKeyFilePath.INSPECTION_DATA_PDF_FIX, Configuration.getConfigurationByName("fileSaveRootPath"));
            if (StringUtils.isNotEmpty(savePath1)) {
                Resource resource = new Resource();
                String resourceName = pic1.getOriginalFilename();
                resource.setPath(savePath1);
                resource.setResourceName(resourceName);
                resource.setResourceTypeEnum(ResourceTypeEnum.PDF);
                resourceBiz.addOrUpdate(resource);
                Set<Resource> resourceSet = new HashSet<>();
                resourceSet.add(resource);
                inspectionData.setEnclosure(resourceSet);
            }
        } else {
            if (inspectionData.getId() != null) {
                inspectionData.setEnclosure(inspectionDataBiz.findModel(inspectionData.getId()).getEnclosure());
            }
        }
        inspectionData.setEnterprise(enterprise);
        inspectionDataBiz.addOrUpdate(inspectionData);
        return ResultUtil.success();
    }

    /**
     * 删除工艺的维保内容
     *
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResultDto delete(String id,HttpServletRequest request) {
        InspectionData inspectionData = inspectionDataBiz.findModel(StringConverters.ToLong(id));
        if(inspectionData==null){
            return ResultUtil.success();
        }
        InspectionTechnology inspectionTechnology = inspectionData.getInspectionTechnology();
        if(inspectionTechnology==null){
            //临时数据 随便删
            inspectionDataBiz.deleteLogic(inspectionData);
            return ResultUtil.success();
        }
        Enterprise enterprise = SessionKeyUtils.getSessionEnterprise(request);
        QueryParam queryParam = new QueryParam();
        queryParam.getSqlMap().put("inspectionTechnologyId",inspectionTechnology.getId()+"");
        queryParam.getSqlMap().put("enterpriseId",enterprise.getId()+"");
        List<InspectionData> inspectionDataList = inspectionDataBiz.findList(queryParam);
        if(CollectionUtils.isNotEmpty(inspectionDataList)&&inspectionDataList.size()>1){
            inspectionDataBiz.deleteLogic(inspectionData);
            return ResultUtil.success();
        }else{
            return ResultUtil.error("请至少保留一个非临时维保内容");
        }

    }
}
